package com.xltt.watchfota;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.basewin.mdm.aidl.AidlSystem;

public class BaseApplication extends Application {
    public static final String SYS_CONFIG_SERVICE = "com.basewin.mdm.SYSTEM_SERVICE";
    public AidlSystem mMyAIDL;
    private boolean isBind = false;

    @Override
    public void onCreate() {
        super.onCreate();
        boolean result = initService();
        Log.d("zhanghui","绑定升级服务结果 = " + result);
    }

    /**
     * 初始化升级服务接口
     */
    private boolean initService(){
        Log.d("zhanghui","开始绑定升级服务");
        Intent intent = new Intent(SYS_CONFIG_SERVICE);
        intent.setPackage("com.pos.mdmservice");
        // 判断有没有服务在启动，兼容8.0
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        return bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMyAIDL = AidlSystem.Stub.asInterface(service);
            isBind = false;
        }

        int t1 = 0;
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMyAIDL = null;
            //如果发生连接失败，那么就重新bind
            if (isBind && t1 < 10) {
                t1++;
                initService();
            } else {
                isBind = false;
            }
        }
    };

    public void unbindService(){
        unbindService(mServiceConnection);
    }

    /**
     * 获取aidl服务
     * @return
     */
    public AidlSystem getAidl(){
        return mMyAIDL;
    }

}
